package com.pingan.license.utils;


import com.pingan.license.deviceinfo.AbstractServerInfos;
import com.pingan.license.deviceinfo.LinuxServerInfos;
import com.pingan.license.deviceinfo.WindowsServerInfos;
import com.pingan.license.model.LicenseCheckModel;
import com.pingan.license.model.LicenseCliModel;
import de.schlichtherle.license.*;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Properties;
import java.util.prefs.Preferences;

/**
 * @AUTHOR:LIUCHAO;
 * @DATE: 2020/12/1 14:47
 */
@Component
public class LicenseVertify {
    private static Logger logger = LogManager.getLogger(LicenseVertify.class);

    public LicenseVertify() {
    }
    @Autowired
    private LicenseCliModel licenseCliModel;
//    public static LicenseVertify licenseVertify;  // 定义一个该类的静态变量
//    @PostConstruct // 使用postconstruct注解，将需要注入的类添加到静态变量中
//    public void init() {
//        licenseVertify = this;
//        licenseVertify.licenseCliModel = this.licenseCliModel;
//    }
    /**
     * 初始化证书的相关参数
     * @param //系统的统一识别码
     * @return
     */
    private LicenseParam initLicenseParams()
    {
        Class<LicenseVertify> clazz=LicenseVertify.class;
        Preferences pre=Preferences.userNodeForPackage(clazz);
        CipherParam cipherParam=new DefaultCipherParam(licenseCliModel.getKeyStorePwd());
        KeyStoreParam pubStoreParam=new DefaultKeyStoreParam(clazz, licenseCliModel.getPubPath(), licenseCliModel.getPubAlias(), licenseCliModel.getKeyStorePwd(), null);
        LicenseParam licenseParam=new DefaultLicenseParam(licenseCliModel.getOnlykey(), pre, pubStoreParam, cipherParam);
        return licenseParam;
    }

    private LicenseManager getLicenseManager()
    {
        return LicenseManagerHolder.getLicenseManager(initLicenseParams());
    }
    /**
     * 安装证书证书
     * @param   //存放证书的路径
     * @return
     */
    public void install(String licdir) {
        try {
            LicenseManager licenseManager=getLicenseManager();
            licenseManager.install(new File(licdir+File.separator+licenseCliModel.getLicName()));
            System.out.println("安装证书成功!");
        }
        catch (Exception e) {
            System.out.println("安装证书失败!");
            e.printStackTrace();
            System.exit(0);
        }

    }
    /**
     * 校验License证书
     * @return boolean
     */
    public boolean verify(){
        LicenseManager licenseManager = LicenseManagerHolder.getLicenseManager(null);
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //2. 校验证书
        try {
            LicenseContent licenseContent = licenseManager.verify();
//            System.out.println(licenseContent.getSubject());
           Boolean result= verifyLicenseCheckModel(licenseContent);
            logger.info(MessageFormat.format("证书校验通过，证书有效期：{0} - {1}",format.format(licenseContent.getNotBefore()),format.format(licenseContent.getNotAfter())));
            return result;
        }catch (Exception e){
            logger.error("证书校验失败！",e);
            return false;
        }
    }

    private Boolean verifyLicenseCheckModel(LicenseContent licenseContent) {
        //证书中的本机信息
        LicenseCheckModel licenseContentExtra = (LicenseCheckModel) licenseContent.getExtra();
        //操作系统类型
        String    osName = System.getProperty("os.name");
        osName = osName.toLowerCase();
        AbstractServerInfos abstractServerInfos = null;
        //根据不同操作系统类型选择不同的数据获取方法
        if (osName.startsWith("windows")) {
            abstractServerInfos = new WindowsServerInfos();
        } else if (osName.startsWith("linux")) {
            abstractServerInfos = new LinuxServerInfos();
        }else{//其他服务器类型
            abstractServerInfos = new LinuxServerInfos();
        }

        //实际的本机信息
        LicenseCheckModel serverInfos =  abstractServerInfos.getServerInfos();
        return compareFields(licenseContentExtra,serverInfos);
    }

    private Boolean compareFields(LicenseCheckModel licenseContentExtra, LicenseCheckModel serverInfos) {
        List ipAddress = licenseContentExtra.getIpAddress();
        List macAddress = licenseContentExtra.getMacAddress();
        String mainBoardSerial = licenseContentExtra.getMainBoardSerial();
        String cpuSerial = licenseContentExtra.getCpuSerial();

        List ipAddress1 = serverInfos.getIpAddress();
        List macAddress1 = serverInfos.getMacAddress();
        String mainBoardSerial1 = serverInfos.getMainBoardSerial();
        String cpuSerial1 = serverInfos.getCpuSerial();
        boolean ipAddressFlag=false;
        for (Object address : ipAddress) {
            for (Object address1 : ipAddress1) {
                if (address.equals(address1)){
                    ipAddressFlag=true;
                    break;
                }
            }
        }
        boolean macAddressFlag=false;
        for (Object address : macAddress) {
            for (Object address1 : macAddress1) {
                if (address.equals(address1)){
                    macAddressFlag=true;
                    break;
                }
            }
        }
        return ipAddressFlag && macAddressFlag
                && mainBoardSerial.equals(mainBoardSerial1)
                && cpuSerial.equals(cpuSerial1);
    }

    /**
     * 卸载证书，在bean从容器移除的时候自动调用
     */
//    public void unInstallLicense() {
//        LicenseManager licenseManager = LicenseManagerHolder.getLicenseManager(null);
//
//            try {
//                licenseManager.uninstall();
//            } catch (Exception e) {
//                // ignore
//
//        }
//    }

}
